package org.sgy.mall.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.sgy.mall.dao.impl.ProductDaoImpl;
import org.sgy.mall.model.Product;

public class ProductServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public ProductServlet() {
	}

	@Override
	public void init() throws ServletException {
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 从数据库中取出商品列表
		ProductDaoImpl productDao = new ProductDaoImpl();
		List<Product> list = productDao.fetchList();
		// 将数据传输到jsp
		request.setAttribute("list", list);
		request.getRequestDispatcher("/product/productList.jsp").forward(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String action = request.getParameter("action");
		if (action.equals("add")) {
			add(request, response);
		}
	}

	private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取参数
		String name = request.getParameter("name");
		String brand = request.getParameter("brand");
		String priceStr = request.getParameter("price");
		int price = 0;
		try {
			price = Integer.parseInt(priceStr);
		} catch (Exception e) {
		}

		// 构建javabean
		Product product = new Product();
		product.setName(name);
		product.setBrand(brand);
		product.setPrice(price);

		// 调用dao
		ProductDaoImpl productDao = new ProductDaoImpl();
		boolean success = productDao.add(product);
		if (success) {
			response.getWriter().println("add product success");
		}
	}

	private void update(HttpServletRequest request, HttpServletResponse response) {

	}
}
